package com.letv.whatslive.mongo;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.letv.whatslive.common.utils.CacheConstants;
import com.letv.whatslive.common.utils.Constants;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.*;
import com.letv.whatslive.model.constant.ProgramConstants;
import com.letv.whatslive.model.convert.ActivityConvert;
import com.letv.whatslive.model.convert.ProgramConvert;
import com.letv.whatslive.model.dto.ActivityDTO;
import com.letv.whatslive.model.dto.ProgramDTO;
import com.letv.whatslive.mongo.dao.*;
import com.letv.whatslive.redis.JedisDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by shenyue on 16-7-4.
 */
@Repository
public class BuildRedis{

    private final static Logger logger = LoggerFactory.getLogger(BuildRedis.class);

    @Autowired
    private ProgramDAO programDAO;
    @Autowired
    private JedisDAO jedisDAO;
    @Autowired
    private ActivityDAO activityDAO;
    @Autowired
    private MenuDAO menuDAO;
    @Autowired
    private CarouselImageSrcDAO carouselImageSrcDAO;
    @Autowired
    private ChipsDAO chipsDAO;


    /**
     * 重建广场页轮播缓存
     * @param op 1表示删除
     */
    public void buildSquareCarouselRedis(Integer op){
        Integer start=0;
        if(Integer.valueOf(1).equals(op))
            start=1;
        List<ProgramDTO> programDTOList = Lists.newArrayList();
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("isCarousel", 1);
        paramMap.put("status", 1);
        paramMap.put("assorts.id",13);
        Map<String, Object> orderMap = Maps.newLinkedHashMap();
        orderMap.put("pType", 1);
        orderMap.put("assorts.priority",-1);
        orderMap.put("createTime",-1);
//        orderMap.put("priority", -1);
//        List<DBObject> dbObjectList = programDAO.selectAll(start, 1, paramMap, orderMap);
        List<Program> programList = programDAO.getProgramListByParamsUnwindCollection(paramMap, orderMap, start, 1);

            if (programList != null) {
            for (Program program : programList) {
                ProgramDTO programDTO = createProgramDTO(program, ProgramConstants.PROGRAM_DTO_TYPE_INDEX);
                programDTOList.add(programDTO);
            }
        }
        if(programDTOList!=null&&!programDTOList.isEmpty())
            jedisDAO.getJedisWriteTemplate().set(CacheConstants.API_SQUARE_CAROUSELS,JSON.toJSONString(programDTOList));
    }

    public void buildSquareCarouselRedis(){
        buildSquareCarouselRedis(null);
    }

    public void buildSquareActivityRedis(){
        Map<String,Object> params = Maps.newHashMap();
        params.put("status", 1);
        DBObject order = new BasicDBObject();
        order.put("priority",-1);
        order.put("_id",-1);
        List<DBObject> list = activityDAO.selectAll(1, 2, params, order);
        List<ActivityDTO> result = Lists.newArrayList();
        Map<String,Object> contentParams = Maps.newHashMap();
        for(DBObject obj : list){
            Activity activity = ActivityConvert.castDBObjectToActivity(obj);
            ActivityDTO activityDTO = new ActivityDTO(activity, "2");
            result.add(activityDTO);
        }
        if(result!=null&&!result.isEmpty())
            jedisDAO.getJedisWriteTemplate().set(CacheConstants.API_SQUARE_ACTIVITYS,JSON.toJSONString(result));
    }

    public void buildSquareAssortsRedis(){
        List<Menu> menuList=null;
        List<Menu> result=Lists.newArrayList();
        Map<String, Object> param=Maps.newLinkedHashMap();
        param.put("status",1);
        param.put("type",1);
        Map<String, Object> order=Maps.newLinkedHashMap();
        order.put("orderNum",1);
        order.put("_id",-1);
        menuList=menuDAO.getMenuListByParams(order,param);
        if(menuList!=null&&!menuList.isEmpty()){
            for(Menu menu:menuList){
                Menu menu1=new Menu();
                menu1.setMenuId(menu.getMenuId());
                menu1.setMenuName(menu.getMenuName());
                menu1.setMenuPicture(menu.getMenuPicture());
                result.add(menu1);
            }
        }
        if(result!=null&&!result.isEmpty())
            jedisDAO.getJedisWriteTemplate().set(CacheConstants.API_SQUARE_ASSORTS,JSON.toJSONString(result));
    }

    public void buildSquareProgramRedis(){
        List<ProgramDTO> programDTOList = Lists.newArrayList();
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("pType", 3);
        paramMap.put("status", 1);
        DBObject orderMap = new BasicDBObject();
        orderMap.put("createTime", -1);
        List<DBObject> dbObjectList = programDAO.selectAll(1, 12, paramMap, orderMap);
        if (dbObjectList != null) {
            for (DBObject dbObject : dbObjectList) {
                ProgramDTO programDTO = createProgramDTO(dbObject, ProgramConstants.PROGRAM_DTO_TYPE_INDEX);
                programDTOList.add(programDTO);
            }
        }
        if(programDTOList!=null&&!programDTOList.isEmpty())
            jedisDAO.getJedisWriteTemplate().set(CacheConstants.API_SQUARE_PROGRAMS,JSON.toJSONString(programDTOList));
    }

    public void buildSquareCarouselImageSrcRedis() {
        Map query = Maps.newHashMap();
        Map order = Maps.newHashMap();
        order.put("priority", -1);
        List<Carousel_ImageSrc> carousel_imageSrcList = carouselImageSrcDAO.getAllCarousel_ImageSrcByParams(order, query);
        List<Carousel_ImageSrc> carouselImageSrcShowList = new ArrayList<Carousel_ImageSrc>();
        if (carousel_imageSrcList != null && carousel_imageSrcList.size() > 0) {
//            int i=0;
            for (Carousel_ImageSrc carousel_imageSrc : carousel_imageSrcList) {
                Carousel_ImageSrc carouselImageSrcShow = new Carousel_ImageSrc();
                carouselImageSrcShow.setPicUrl(carousel_imageSrc.getPicUrl());
                carouselImageSrcShow.setType(carousel_imageSrc.getType());
                carouselImageSrcShow.setBusiId(carousel_imageSrc.getBusiId());
                carouselImageSrcShow.setAdUrl(carousel_imageSrc.getAdUrl());
                carouselImageSrcShowList.add(carouselImageSrcShow);
//                i++;
//                if(i==1)
//                    break;
            }
        }
        try {
            jedisDAO.getJedisWriteTemplate().set(CacheConstants.API_SQUARE_CAROUSELIMAGE, JSON.toJSONString(carouselImageSrcShowList));

        } catch (Exception e) {
            logger.error("writeCacheCarouselImageSrc failed!", e);
        }
    }

    public void BuildSquareProgramRedis(Chips chips){
        Map<String,Object> query=Maps.newHashMap();
        Map<String,Object> sort=Maps.newLinkedHashMap();
        List<Program> programList=Lists.newArrayList();
        List<ProgramDTO> programDTOList=Lists.newArrayList();
        query.put("tag",chips.getTag());
        sort.put("priority",-1);
        List<Chips> chipsList=chipsDAO.getChipsListByParams(sort,query, 0, Constants.SQUARE_PROGRAM_COUNT);
        if(chipsList==null||chipsList.isEmpty()){
            logger.error("judgeAndRebuildSquareCarouselRedis failed chipsList is null");
            return;
        }
        for(Chips chips1:chipsList){
            if(StringUtils.isBlank(chips1.getBusiId())){
                logger.error("judgeAndRebuildSquareCarouselRedis failed chips1.busiId is null");
                return;
            }
            Program program=programDAO.getProgramById(ObjectUtils.toLong(chips1.getBusiId()));
            if(program==null){
                logger.error("judgeAndRebuildSquareCarouselRedis failed chips1.busiId is null");
                return;
            }
            ProgramDTO programDTO=createProgramDTO(program,ProgramConstants.PROGRAM_DTO_TYPE_INDEX);
            programDTOList.add(programDTO);
        }
        if(programDTOList!=null&&!programDTOList.isEmpty())
            jedisDAO.getJedisWriteTemplate().set(CacheConstants.API_SQUARE_PROGRAMS,JSON.toJSONString(programDTOList));
    }

    public void BuildSquareCarouselImageSrcRedis(Chips chips){
        Map<String,Object> query=Maps.newHashMap();
        Map<String,Object> sort=Maps.newLinkedHashMap();
        List<Program> programList=Lists.newArrayList();
        List<ProgramDTO> programDTOList=Lists.newArrayList();
        query.put("tag",chips.getTag());
        sort.put("priority",-1);
        List<Chips> chipsList=chipsDAO.getChipsListByParams(sort,query,0,Constants.SQUARE_CAROUSELIMAGE_COUNT);
        if(chipsList==null||chipsList.isEmpty()){
            logger.error("judgeAndRebuildSquareCarouselRedis failed chipsList is null");
            return;
        }
        List<Carousel_ImageSrc> carouselImageSrcShowList = new ArrayList<Carousel_ImageSrc>();

        for (Chips chips1 : chipsList) {
            Carousel_ImageSrc carouselImageSrcShow = new Carousel_ImageSrc();
            carouselImageSrcShow.setPicUrl(chips1.getPicUrl());
            carouselImageSrcShow.setType(chips1.getType());
            carouselImageSrcShow.setBusiId(chips1.getBusiId());
            carouselImageSrcShow.setAdUrl(chips1.getAdUrl());
            carouselImageSrcShowList.add(carouselImageSrcShow);
//                i++;
//                if(i==1)
//                    break;
        }
        try {
            jedisDAO.getJedisWriteTemplate().set(CacheConstants.API_SQUARE_CAROUSELIMAGE, JSON.toJSONString(carouselImageSrcShowList));

        } catch (Exception e) {
            logger.error("writeCacheCarouselImageSrc failed!", e);
        }
    }

    public void judgeAndRebuildSquareChipsRedis(Chips chips){
        if(chips==null)
        {
            logger.error("judgeAndRebuildSquareChipsRedis failed program is null");
            return;
        }
        if(Constants.CHIPS_SQUARE_PROGRAM.equals(chips.getTag())){
            BuildSquareProgramRedis(chips);
        }
        else if(Constants.CHIPS_SQUARE_CAROUSELIMAGE.equals(chips.getTag())){
            BuildSquareCarouselImageSrcRedis(chips);
        }
    }

    public void judgeAndRebuildSquareProgramRedis(Program program){
        if(program==null)
        {
            logger.error("judgeAndRebuildSquareProgramRedis failed program is null");
            return;
        }
        Map<String,Object> query=Maps.newHashMap();
        List<Program> programList=Lists.newArrayList();
        List<ProgramDTO> programDTOList=Lists.newArrayList();
        String strProgramList=jedisDAO.getJedisReadTemplate().get(CacheConstants.API_SQUARE_PROGRAMS);
        if(StringUtils.isNotBlank(strProgramList)){
            programDTOList=JSON.parseArray(strProgramList,ProgramDTO.class);
            if(programDTOList==null||programDTOList.isEmpty())
                return;
        }
        for(ProgramDTO programDTO:programDTOList){
            if(programDTO.getId().equals(program.getId())){
                Chips chips=new Chips();
                chips.setTag(Constants.CHIPS_SQUARE_PROGRAM);
                judgeAndRebuildSquareChipsRedis(chips);
                return;
            }
        }
    }

//    /**
//     * 判断是否需要重建轮播缓存，如需要则重建
//     * @param program
//     * @param op 操作，1为删除
//     */
//    public void judgeAndRebuildSquareCarouselRedis(Program program,Integer op){
//        if(program==null)
//        {
//            logger.error("judgeAndRebuildSquareCarouselRedis failed program is null");
//            return;
//        }
//        List<ProgramDTO> carouselList=Lists.newArrayList();
//        String strCarouselList=jedisDAO.getJedisReadTemplate().get(CacheConstants.API_SQUARE_CAROUSELS);
//        if(org.apache.commons.lang3.StringUtils.isNotBlank(strCarouselList)){
//            carouselList=JSON.parseArray(strCarouselList,ProgramDTO.class);
//        }
//        if(carouselList==null||carouselList.isEmpty())
//        {
//            logger.error("judgeAndRebuildSquareCarouselRedis failed carousel redis is null,programId is:"+program.getId());
//            return;
//        }
////        if(program.getStatus()==0||Integer.valueOf(1).equals(op)){
//        //判断是否缓存里是此轮播，如果是则重建
//        if(carouselList.get(0).getId().equals(program.getId())) {
//            if(Integer.valueOf(1).equals(op))
//                buildSquareCarouselRedis(1);
//            else
//                buildSquareCarouselRedis();
//            return;
//        }
////        }
//        if(program.getStatus()==1||program.getStatus()==-1){
//            Program program1=programDAO.getProgramById(carouselList.get(0).getId());
//            if(program1!=null){
//                if(program1.getPriority().longValue()<program.getPriority().longValue())
//                    buildSquareCarouselRedis();
//            }
//            else
//                buildSquareCarouselRedis();
//        }
//    }

    public void judgeAndRebuildSquareActivityRedis(Activity activity) {
        if(activity==null)
        {
            logger.error("judgeAndRebuildSquareActivityRedis failed activity is null");
            return;
        }
        List<ActivityDTO> activityDTOs=Lists.newArrayList();
        String strActivityList=jedisDAO.getJedisReadTemplate().get(CacheConstants.API_SQUARE_ACTIVITYS);
        if(org.apache.commons.lang3.StringUtils.isNotBlank(strActivityList)){
            activityDTOs=JSON.parseArray(strActivityList,ActivityDTO.class);
        }
        if(activityDTOs==null||activityDTOs.isEmpty())
        {
            logger.error("judgeAndRebuildSquareActivityRedis failed activity redis is null,activity is:"+activity.getId());
            return;
        }
//        if(activity.getStatus()==0){
        //是否缓存里是此轮播，如果是则重建
        for(ActivityDTO activityDTO:activityDTOs){
            if(activityDTO.getId().equals(activity.getId())) {
                buildSquareActivityRedis();
                return;
            }
        }
//        }
//        else{
        for(ActivityDTO activityDTO:activityDTOs){
            Activity activity1=activityDAO.getActivityById(activityDTO.getId());
            if(activity1.getPriority().longValue()<activity.getPriority().longValue()){
                buildSquareActivityRedis();
                break;
            }
        }
//        }
    }

    /**
     * 创建ProgramDTO
     *
     * @param dbObject
     * @param dtoType  DTO类型
     * @return
     */
    public ProgramDTO createProgramDTO(DBObject dbObject, Integer dtoType) {

        Program program = ProgramConvert.castDBObjectToProgram(dbObject);
        return createProgramDTO(program,dtoType);
    }

    /**
     * 创建ProgramDTO
     *
     * @param program
     * @param dtoType  DTO类型
     * @return
     */
    public ProgramDTO createProgramDTO(Program program, Integer dtoType) {

        // 设定视频参与信息
        setInvolInfor(program);

        ProgramDTO programDTO = new ProgramDTO(program, dtoType);

        // 设定活动信息
        List<Map<String, Object>> activityList = program.getActivity();
        if (activityList != null) {

            for (Map<String, Object> activity : activityList) {

                Long actId = ObjectUtils.toLong(activity.get("id"));
                String activityInfo = ObjectUtils.toString(jedisDAO.getJedisReadTemplate().get(CacheConstants.API_ACTIVITY_JSON + actId), "");

                if (!"".equals(activityInfo)) {

                    Map<String, Object> activtiyInfoMap = JSON.parseObject(activityInfo, Map.class);
                    activity.put("tag", ObjectUtils.toString(activtiyInfoMap.get("tag"), "")); // 标签
                    activity.put("iconUrl", ObjectUtils.toString(activtiyInfoMap.get("iconUrl"), "")); // 角标
                    activity.put("copyWriter", ObjectUtils.toString(activtiyInfoMap.get("copyWriter"), "")); // 分享文案
                }
                activity.remove("priority");
            }

            Collections.reverse(activityList);
        }
        programDTO.setActivityList(activityList);

        // 设定节目类型
        Integer pType = program.getPType();
        Integer status = program.getStatus();
        Integer pType2 = program.getPType(); // 节目类型2 1:直播 2:预约 3:点播 4:秒转
        if (pType == 3 && status == -1) {

            pType2 = 4;
        }
        programDTO.setPType2(pType2);

        return programDTO;
    }

    /**
     * 设定视频参与信息
     *
     * @param program
     */
    public void setInvolInfor(Program program) {

        // 当为直播时使用在线数据
        if (program.getPType() == 1) {

            // 点赞数
            Long baseLikeNum = ObjectUtils.toLong(jedisDAO.getJedisReadTemplate().hget(CacheConstants.PROGRAM_BASE_LIKENUM, ObjectUtils.toString(program.getId())), 0L);
            Long likeNum = ObjectUtils.toLong(jedisDAO.getJedisReadTemplate().get(Constants.LIVE_ONLINE_LIKE_KEY + program.getId()), 0L);
            program.setLikeNum(baseLikeNum + likeNum);

            // 评论数
            program.setCommentNum(ObjectUtils.toLong(jedisDAO.getJedisReadTemplate().get(Constants.LIVE_ONLINE_COMMENT_KEY + program.getId()), 0l));

            Long baseNum = ObjectUtils.toLong(jedisDAO.getJedisReadTemplate().hget(CacheConstants.PROGRAM_BASE_WATCHNUM, ObjectUtils.toString(program.getId())), 0L);

            // 观看人数
            Long watchNum = ObjectUtils.toLong(jedisDAO.getJedisReadTemplate().zcard(Constants.LIVE_ONLINE_USER_LIST_KEY + program.getId()), 0L);
            program.setWatchNum(baseNum + watchNum);

            // 观看人次
            Long watchCount = ObjectUtils.toLong(jedisDAO.getJedisReadTemplate().get(Constants.LIVE_ONLINE_WATCH_KEY + program.getId()), 0L);
            program.setWatchCount(baseNum + watchCount);
        }
    }
}
